package datastructure.stack;

import java.util.Stack;

/**
 * @author jack.wu
 * @version 1.0
 * @date 2020-03-22
 */
public class ReversePoland {

    public static void main(String[] args) {
        String expression = "3 4 + 5 * 6 -";
        int res = calculation(expression);
        System.out.println(res);
    }

    private static int calculation(String expression) {

        String[] split = expression.split(" ");
        Stack<String> numStack = new Stack<>();
        for (String item : split){
            // 匹配多位数
            if (item.matches("\\d+")){
                numStack.push(item);
            }else {
                int num2 = Integer.parseInt(numStack.pop());
                int num1 = Integer.parseInt(numStack.pop());
                int res = 0;
                switch (item) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2;
                        break;
                    case "*":
                        res = num1 * num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                    default:
                        throw new RuntimeException("运算符暂无定义~~~~");
                }
                numStack.push(res+"");
            }
        }
        // 最后栈中的数就是结果
        return Integer.parseInt(numStack.pop());
    }

}

